'''
Created on 2020年3月3日

@author: Administrator
'''
import datetime

from dateutil.relativedelta import relativedelta
from flask import json
from peewee import JOIN, fn

from common.public import *
from orm.model import User, MyCustomer, Customer, TrackRecord, Dept, Notify, db, \
    SummaryTrack
from view.baseview import BaseView


class MyCustomerView(BaseView):
    def __init__(self):
        pass

    def queryMyCustomer(self, params):
        """根据条件取得我的客户列表，params：条件参数"""
        result=[]
        where_condition = True
        if params["keyword"]:
            likestr= "%"+params["keyword"] +"%"
            where_condition=(Customer.compname ** likestr )
            where_condition=where_condition | (Customer.legalperson** likestr )
            where_condition=where_condition | (Customer.address** likestr )
            where_condition=where_condition | (Customer.phone** likestr )
            where_condition=where_condition | (MyCustomer.memo** likestr )
        if params["saletype"]:
            where_condition=where_condition &(MyCustomer.saletype.in_(params["saletype"]))
        if params["assignetype"]:
            where_condition = where_condition & (MyCustomer.customer.assignetype.in_(params["assignetype"]))
        if params["src"]:
            where_condition=where_condition &(MyCustomer.customer.src.in_(params["src"]))
        if params["signtype"]:
            where_condition=where_condition &(MyCustomer.signtype.in_(params["signtype"]))
        if params["weixin"]:
            where_condition=where_condition &(MyCustomer.weixin.in_(params["weixin"]))
        
        # 取得部门管辖区域
        user = User.get(User.id == params["userid"])
        deptids = Dept.select(Dept.id).where(Dept.up_id==user.dept_id)
        leader = User.select().where(User.id==params["userid"]).first()

        if params["outdate"]==MYCUSTOMER_PICK_OUTDATE:
            where_condition=where_condition &(MyCustomer.customer.dept==user.dept)
        else:
            if deptids:
                # 总经办
                pass
            else:
                ids = []
                if leader.ismanager == COMMON_TRUE:
                    # 如果是经理
                    where_condition=where_condition &(MyCustomer.customer.dept==user.dept)
                elif leader.isleader == COMMON_TRUE:
                    # 如果是主管
                    rows = User.select(User.id).where(User.leader_id==params["userid"])
                    for row in rows:
                        ids.append(row.id)
                    if params["userid"] not in ids:
                        ids.append(params["userid"])
                    where_condition=where_condition &(MyCustomer.tracker.in_(ids))
                else:
                    # 如果是员工
                    where_condition=where_condition &(MyCustomer.tracker_id == params["userid"])
                        
        if params["tracker"]:
            where_condition=where_condition &(MyCustomer.tracker.in_(params["tracker"]))

        if params["outdate"]==MYCUSTOMER_PICK_OUTDATE:
            # 捡漏池只显示来源是线索、分配方式是手动、销售分类是ABC的客户
            where_condition=where_condition &((MyCustomer.status== MYCUSTOMER_STATUS_EXPIRE) | (MyCustomer.status== MYCUSTOMER_STATUS_FREE)) \
                            & ((Customer.src== CUSTOMER_SRC_XIANSUO) | (Customer.assignetype == CUSTOMER_ASSIGNETYPE_MANUAL)\
                               | (MyCustomer.saletype == SALE_TYPE_A) | (MyCustomer.saletype == SALE_TYPE_B) | (MyCustomer.saletype == SALE_TYPE_C))
        else:
            if params["status"]:
                where_condition=where_condition &(MyCustomer.status.in_(params["status"]))
            # 不检漏时，不显示释放和过期客户
            where_condition = where_condition & (MyCustomer.status != MYCUSTOMER_STATUS_EXPIRE) \
            & (MyCustomer.status!= MYCUSTOMER_STATUS_FREE)


        if params["datetime"]:
            where_condition=where_condition & ((MyCustomer.adddatetime >= params["datetime"][0] +" 00:00:00") & (MyCustomer.adddatetime <= params["datetime"][1] +" 23:59:59") )
        if params["updatetime"]:
            where_condition=where_condition & ((MyCustomer.updatetime >= params["updatetime"][0] +" 00:00:00") \
                                               & (MyCustomer.updatetime <= params["updatetime"][1] +" 23:59:59") )
        total = MyCustomer.select().join(Customer, JOIN.RIGHT_OUTER, on=(Customer.id == MyCustomer.customer_id)).where(where_condition).count()
        rows = MyCustomer.select().join(Customer, JOIN.RIGHT_OUTER, on=(Customer.id == MyCustomer.customer_id))\
            .where(where_condition).order_by(MyCustomer.adddatetime.desc())\
            .paginate(int(params["pageNo"]), int(params["pagesize"]))
        print(rows)
        for row in rows:
            recs =[]
            for rec in row.trackrecord_set.order_by(TrackRecord.createtime.desc()):
                recs.append({"id":rec.id, "createtime":str(rec.createtime),"tracktype":rec.tracktype,"content":rec.content})
            if recs.__len__()==0:
                recs.append({"id":"", "createtime":"无","tracktype":"无","content":"无跟踪记录"})
            #print("ID:",row.customer.id)

            data = {
                "id":row.id,
                "customerid":row.customer.id,
                "name":row.customer.compname,
                "founddate":str(row.customer.founddate),
                "legalperson":row.customer.legalperson,
                "contacter":row.customer.contacter,
                "area":row.customer.area,
               "address":row.customer.address,
               "phone":row.customer.phone,
               "saletype":row.saletype,
               "weixin":row.weixin,
               "adddatetime":str(row.adddatetime),
               "enddatetime":str(row.enddatetime),
               "assignetype":row.customer.assignetype,
               "src":row.customer.src,
               "signtype":row.signtype,
                "status":row.status,
               "trackerid":row.tracker.id,
               "trackername":row.tracker.username,
               "updatetime":str(row.updatetime),
              "memo":row.memo,
               "amount":row.amount,
              "actualcollection":row.actualcollection,
              "balance":row.balance,
              "balancecondtion":row.balancecondtion,
              "recs":recs
             }
            result.append(data )
        return super().resultSet(200, "", result,total=total)
    
    def getTrackers(self,userid):
        """取得跟踪者列表"""
        result=[]
        leader = User.select().where(User.id==userid).first()
        # 如果是主管
        if leader.isleader == COMMON_TRUE:
            #查是否有子部门 仅支持一层子部门
            sub_depts = Dept.select().where(Dept.up_id==leader.dept_id)
            deptids = []
            for dept in sub_depts:
                deptids.append(dept.id)
            deptids.append(leader.dept_id)
            rows = User.select().where(User.dept_id.in_(deptids)).order_by(User.username.desc())
            for row in rows:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                result.append(data )
        else:
            rows = User.select().where(User.id==userid).order_by(User.username.desc())
            for row in rows:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                result.append(data )
        return super().resultSet(200, "跟踪者列表取得成功", result)

    def isAssig2MyCustomer(self, customerid):
            # 在我的客户中找到已分配的客户
            count = MyCustomer.select().where((MyCustomer.customer==customerid) & (MyCustomer.status!= MYCUSTOMER_STATUS_FREE)\
                                                       & (MyCustomer.status!= MYCUSTOMER_STATUS_EXPIRE)& (MyCustomer.status!= MYCUSTOMER_STATUS_FORBIDDEN)).count()
            if count > 0:
                # 如果已经分配给跟踪者
                return True
            else:
                return False
    
    def checkCompNameDistinct(self, id,name):
        """
        检查公司名称有没有重复
        """
        data = {"id":-1}
        checkPass = super().resultSet(200, "公司名称检查通过", data)
        compnameNopass = super().resultSet(420, "公共客户中已经存在该公司名称，如要将该公司分配给自己，请与主管联系。", data)
        compnamefind = Customer.select().where(Customer.compname==name).first()
        if compnamefind:
            if compnamefind.id == id:
                '''编辑时id传当前选择的Customerid'''
                return checkPass
            else:
                '''添加时id传空'''
                data["id"] = compnamefind.id
                return compnameNopass
        return checkPass
     
    def checkPhoneDistinct(self, id, phone):
        """
        检查电话号码有没有重复
        """
        checkPass = super().resultSet(200, "检查电话号码通过", {})
        phoneNopass = super().resultSet(420, "电话不能重复。", {})
        phonfind = Customer.select().where(Customer.phone==phone).first()
        if phonfind:
            if phonfind.id == id:
                return checkPass
            else:
                return phoneNopass
        else:
            return checkPass
         
    @db.atomic()                   
    def updateMyCustomer(self, params):
        """
        更新
        """
        # checkname = self.checkCompNameDistinct(params["customerid"],params["name"])
        # if checkname["code"] == 200:
        content_str = ""
        for rec in params["recs"]:
            # 找到修改客户类别
            if rec["filedname"]=="saletype":
                saletype = rec["valueChanged"]
            elif rec["filedname"]=="src":
                src = rec["valueChanged"]
            # 修改记录
            content_str = content_str + CHANGED_COLUMNS[rec["filedname"]] + ":" + str(rec["valueOrg"]) +"->" + str(rec["valueChanged"]) + ";"
        # 找到我的客户
        mycustomer=MyCustomer.get(MyCustomer.id==params["id"])
        mycustomer.saletype=params["saletype"]
        mycustomer.weixin = params["weixin"]
        mycustomer.tracker_id =params["trackerid"]
        mycustomer.status=params["status"]
        mycustomer.amount=params["amount"]
        mycustomer.actualcollection=params["actualcollection"]
        mycustomer.balance=params["balance"]
        mycustomer.balancecondtion=params["balancecondtion"]
        mycustomer.updatetime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        if params["status"] == MYCUSTOMER_STATUS_SIGNED:
            mycustomer.saletype = SALE_TYPE_S
        else:
            mycustomer.saletype=params["saletype"]
        mycustomer.memo=params["memo"]

#             # 找到跟踪日期
#             tarck = TrackRecord.select().where(TrackRecord.mycustomer_id ==params["id"]).order_by(TrackRecord.createtime.desc()).first()
#             if tarck:
#                 createtime = tarck.createtime
#             else:
#                 createtime = mycustomer.adddatetime
        enddatetime_str =self.getEnddatetime(datetime.datetime.now(),params["saletype"],params["src"] )
        mycustomer.enddatetime=enddatetime_str
        mycustomer.save()
        # 找到公共客户
        customer = Customer.get(Customer.id==params["customerid"])
        customer.compname=params["name"]
        customer.legalperson=params["legalperson"]
        customer.contacter=params["contacter"]
        customer.area = params["area"]
        customer.address=params["address"]
        customer.phone=params["phone"]
        customer.src=params["src"]
        customer.save()
        #添加修改记录
        TrackRecord.create(
            mycustomer_id = mycustomer.id,
            tracktype = TRACK_EDIT,
            createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
            content = content_str
        )
        # 判定是否为客户降级
        type_str = ""
        if  "A->B" in content_str or  "A->C" in content_str  or  "A->无" in content_str  or "B->C" in content_str  or  "B->无" in content_str:
            content_str ="客户："+ params["name"] +"被降级，" + content_str,
            type_str = NOTIFY_TYPE_CUSTOMER_CHANGED
        if type_str!="":
            #找到部门主管发送通知
            user = User.get(User.id==params["trackerid"])
            print(user.leader_id)
            if(user.leader_id!=None):
                Notify.create(
                    notifier_id = user.leader_id,
                    createdatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                    type = type_str,
                    content = content_str,
                    status = NOTIFY_STATUS_UDPRESSED,
                    tracker_id = params["trackerid"],
                    memo = ""
                )
        #业务统计：跟踪数量，微信，ABC，签约，面访，金额等
        self.summaryForUpdate(params)

        return super().resultSet(200, "更新成功", [])
#             else:
#                 return checkphone
#         else:
#             return checkname
        raise Exception("更新失败")
    
    @db.atomic()                   
    def createSummaryData(self, trackerid):
    # 业务统计：跟踪数量，微信，ABC，签约，面访，金额等  START
        sdate = time.strftime("%Y-%m", time.localtime()) + '-01 00:00:00'
        edate = str(datetime.datetime.strptime(sdate,'%Y-%m-%d %H:%M:%S').date() + relativedelta(months=1)) + ' 00:00:00'
        delta = datetime.datetime.strptime(edate, '%Y-%m-%d %H:%M:%S') - datetime.datetime.strptime(sdate, '%Y-%m-%d %H:%M:%S')
        #print(delta.days)
        stcondtion = (SummaryTrack.tracker == trackerid) & ((SummaryTrack.date >= sdate) & (SummaryTrack.date < edate))
        stcount = SummaryTrack.select().where(stcondtion).count()
        if stcount < delta.days:
            # 如果当月的初始数据不存在，就创建一个月的数据都为0
            count = 0
            while count <  delta.days:
                curdate = datetime.datetime.strptime(sdate,'%Y-%m-%d %H:%M:%S').date() + relativedelta(days=count)
                find = SummaryTrack.select().where((SummaryTrack.tracker==trackerid) & (SummaryTrack.date==curdate))
                if find:
                    continue
                else:
                    SummaryTrack.create(
                        tracker_id=trackerid,
                        date = curdate
                    )
                count = count + 1
    
    @db.atomic()                   
    def summaryForAdd(self, params):
        """
        业务统计：跟踪数量，微信，ABC，签约，面访，金额等
        """
        # 创建统计数据
        self.createSummaryData(params["trackerid"])
        
        # 取得当前日期的跟踪数据
        curdaycondtion = (SummaryTrack.tracker == params["trackerid"]) & (SummaryTrack.date == time.strftime("%Y-%m-%d", time.localtime()))
        strack = SummaryTrack.get(curdaycondtion)
        # 取得当前修改字段
        if "weixin" in params:
            if params["weixin"] == MYCUSTOMER_WEIXIN_ADDED:
                strack.weixin = strack.weixin + 1
        if "saletype" in params:
            if params["saletype"] == SALE_TYPE_A:
                strack.A =strack.A+1
            elif params["saletype"] == SALE_TYPE_B:
                strack.B = strack.B +1
            elif params["saletype"] == SALE_TYPE_C:
                strack.C =strack.C +1
        if "signtype" in params:
            if params["signtype"] == CUSTOMER_SIGNED_SINGNEW:
                strack.signnew =strack.signnew +1
            elif params["signtype"] == CUSTOMER_SIGNED_SINGCONTINUE:
                strack.signcontinue =strack.signcontinue+ 1
            elif params["signtype"]== CUSTOMER_SIGNED_SINGOLD:
                strack.signold =strack.signold +1
        if "status" in params:
            if params["status"] == MYCUSTOMER_STATUS_VISITED:
                strack.visited =strack.visited +1
            elif params["status"] == MYCUSTOMER_STATUS_SIGNED:
                strack.signed =strack.signed +1
#         if "amount" in params:   
#             strack.amount =strack.amount +int(params["amount"])
#         if "actualcollection" in params:   
#             strack.actualcollection =strack.actualcollection+ int(params["actualcollection"])
#         if "balance" in params:   
#             strack.balance =strack.balance +int(params["balance"])
        # 批量添加时，不计入跟踪量
        if "isbatch" in params:
            # 批量添加
            pass
        else:
            strack.total =strack.total + 1
        strack.save()

    @db.atomic()                   
    def summaryForUpdate(self, params):
        """
        业务统计：跟踪数量，微信，ABC，签约，面访，金额等
        """
                # 创建统计数据
        self.createSummaryData(params["trackerid"])

        # 取得当前日期的跟踪数据
        curdaycondtion = (SummaryTrack.tracker == params["trackerid"]) & (SummaryTrack.date == time.strftime("%Y-%m-%d", time.localtime()))
        strack = SummaryTrack.get(curdaycondtion)
        for rec in params["recs"]:
            # 取得当前修改字段
            if rec["filedname"]=="weixin":
                if rec["valueChanged"] == MYCUSTOMER_WEIXIN_ADDED:
                    strack.weixin = strack.weixin + 1
            elif rec["filedname"]=="saletype":
                if rec["valueChanged"] == SALE_TYPE_A:
                    strack.A = strack.A + 1
                elif rec["valueChanged"] == SALE_TYPE_B:
                    strack.B = strack.B + 1
                elif rec["valueChanged"] == SALE_TYPE_C:
                    strack.C = strack.C + 1
            elif rec["filedname"]=="signtype":
                if rec["valueChanged"] == CUSTOMER_SIGNED_SINGNEW:
                    strack.signnew = strack.signnew + 1
                elif rec["valueChanged"] == CUSTOMER_SIGNED_SINGCONTINUE:
                    strack.signcontinue = strack.signcontinue + 1
                elif rec["valueChanged"] == CUSTOMER_SIGNED_SINGOLD:
                    strack.signold = strack.signold + 1
            elif rec["filedname"]=="status":
                if rec["valueChanged"] == MYCUSTOMER_STATUS_VISITED:
                    strack.visited = strack.visited + 1
                elif rec["valueChanged"] == MYCUSTOMER_STATUS_SIGNED:
                    strack.signed = strack.signed + 1
                elif rec["valueChanged"] == MYCUSTOMER_STATUS_TRANSED:
                    strack.moveto = strack.moveto + 1
#             elif rec["filedname"]=="amount":
#                 strack.amount = strack.amount + rec["valueChanged"]
#             elif rec["filedname"]=="actualcollection":
#                 strack.actualcollection = strack.actualcollection + rec["valueChanged"]
#             elif rec["filedname"]=="balance":
#                 strack.balance = strack.balance + rec["valueChanged"]

        strack.total = strack.total + 1
        strack.save()

#     @db.atomic()                   
#     def summaryForMovetoAdd(self, trackerid, mycus):
#         '''转移的客户，加到跟踪者统计信息中'''
#         # 创建统计数据
#         self.createSummaryData(mycus.tracker_id)
# 
#         # 取得当前日期的跟踪数据
#         curdaycondtion = (SummaryTrack.tracker == trackerid) & (SummaryTrack.date == time.strftime("%Y-%m-%d", time.localtime()))
#         strack = SummaryTrack.get(curdaycondtion)
#         # 取得当前修改字段
#         if mycus.weixin == MYCUSTOMER_WEIXIN_ADDED:
#             strack.weixin = strack.weixin + 1
#         if mycus.saletype == SALE_TYPE_A:
#             strack.A = strack.A + 1
#         elif mycus.saletype == SALE_TYPE_B:
#             strack.B = strack.B + 1
#         elif mycus.saletype == SALE_TYPE_C:
#             strack.C = strack.C + 1
#         if mycus.signtype == CUSTOMER_SIGNED_SINGNEW:
#             strack.signnew = strack.signnew + 1
#         elif mycus.signtype == CUSTOMER_SIGNED_SINGCONTINUE:
#             strack.signcontinue = strack.signcontinue + 1
#         elif mycus.signtype == CUSTOMER_SIGNED_SINGOLD: 
#             strack.signold = strack.signold + 1
#         if mycus.status == MYCUSTOMER_STATUS_SIGNED:
#             strack.signed = strack.signed + 1
#         elif mycus.status == MYCUSTOMER_STATUS_VISITED:
#             strack.visited = strack.visited + 1
#         strack.save()
        
    @db.atomic()
    def addMyCustomer(self, params):
        """
        添加我的客户
        """
        cur_date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # 计算截止日期
        enddatetime_str = self.getEnddatetime(datetime.datetime.now(), params["saletype"], params["src"])

        amount = 0
        actualcollection = 0
        balance = 0
        balancecondtion = "无"
        if "amount" in params:
            amount = params["amount"]
        if "actualcollection" in params:
            actualcollection = params["actualcollection"]
        if "balance" in params:
            balance = params["balance"]
        if "balancecondtion" in params:
            balancecondtion = params["balancecondtion"]
        stype = ''
        if params["status"] == MYCUSTOMER_STATUS_SIGNED:
            stype = SALE_TYPE_S
        else:
            stype = params["saletype"]
        checkname = self.checkCompNameDistinct(params["id"],params["name"])
#         checkphone = self.checkPhoneDistinct(params["id"],params["phone"])
        # 取得部门
        if params["trackerid"]:
            user = User.get(User.id == params["trackerid"])

        # 找到已被分配客户
        fpcustomer = MyCustomer.select().join(Customer, JOIN.RIGHT_OUTER, on=(Customer.id == MyCustomer.customer_id)) \
            .where(((MyCustomer.status == MYCUSTOMER_STATUS_UNSIGNED) | (MyCustomer.status == MYCUSTOMER_STATUS_VISITED) \
                   | (MyCustomer.status == MYCUSTOMER_STATUS_TRACKED)) & (Customer.compname == params["name"])).count()
        print(fpcustomer)
        if fpcustomer == 0:
            '''如果客户在公共客户中不存在'''
            customer = Customer.create(
                compname=params["name"],
                legalperson=params["legalperson"],
                contacter=params["contacter"],
                area = params["area"],
                address=params["address"],
                phone=params["phone"],
#                     founddate =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                createdatetime =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                updatetime =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                assignetype=CUSTOMER_ASSIGNETYPE_MANUAL,
                src=params["src"],
                status=CUSTOMER_STATUS_NORMAL,
                dept_id =user.dept_id
                )

            mycustomer = MyCustomer.create(
                customer_id = customer.id,
                saletype=stype,
                weixin = params["weixin"],
                adddatetime=cur_date_str,
                enddatetime =enddatetime_str,
                updatetime =time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                tracker_id =params["trackerid"],
                status = params["status"],
                amount=amount,
                actualcollection=actualcollection,
                balance=balance,
                balancecondtion=balancecondtion,
                signtype=params["signtype"],
                memo=params["memo"]
                )
            # 添加修改记录
            TrackRecord.create(
                mycustomer_id=mycustomer.id,
                tracktype=TRACK_ADD,
                createtime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                content=params["memo"]
            )

        else:
            '''如果客户在公共客户中存在'''
            # 如果已经分配给跟踪者
            return super().resultSet(400, "客户已经分配给其他跟踪者！请与部门主管联系！", [])

        # 业务统计
        self.summaryForAdd(params)
        
        return super().resultSet(200, "添加成功", [])
        raise Exception("添加失败")
    
    def getEnddatetime(self, createtime,saletype,src):
        '''取得过期时间'''
        #计算截止日期
        if saletype==SALE_TYPE_NONE:
            if src== CUSTOMER_SRC_XIANSUO:
                # 手动分配客户线索客户30M期限
                enddatetime_str = (createtime+datetime.timedelta(minutes=SALE_TYPE_30M)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                # 无类别客户手动4h期限
                enddatetime_str = (createtime+datetime.timedelta(hours=SALE_TYPE_4HOUR)).strftime("%Y-%m-%d %H:%M:%S")
        elif saletype==SALE_TYPE_A:
            # A类别客户7天期限
            enddatetime_str = (createtime+datetime.timedelta(days=SALE_TYPE_7DAY)).strftime("%Y-%m-%d %H:%M:%S")
        elif saletype==SALE_TYPE_B:
            # B类别客户14天期限
            enddatetime_str = (createtime+datetime.timedelta(days=SALE_TYPE_15DAY)).strftime("%Y-%m-%d %H:%M:%S")
        elif saletype==SALE_TYPE_C:
            # C类别客户30天期限
            enddatetime_str = (createtime+datetime.timedelta(days=SALE_TYPE_30DAY)).strftime("%Y-%m-%d %H:%M:%S")
        else:
            # 无类别客户1天期限
            enddatetime_str = (createtime+datetime.timedelta(days=SALE_TYPE_1DAY)).strftime("%Y-%m-%d %H:%M:%S")
        return enddatetime_str
                
    @db.atomic()                   
    def addFromCustomerRandom(self, params):
        """
        从公共客户中随机取得添加到我的客户
        """
        # 取得部门管辖区域
        user = User.get(User.id == params['userid'])
        
        count = MyCustomer.select().where((MyCustomer.tracker_id==params['userid']) \
                                          & (MyCustomer.adddatetime.between(datetime.date.today(),\
                                        datetime.date.today() + datetime.timedelta(days=1)))).count()
        if count >= SALE_CUSTOMER_MAX:
            return super().resultSet(400, "每天只能添加"+str(SALE_CUSTOMER_MAX)+"个客户", [])
        # 随机取100个公共 客户未分配并且备注是空的
        conditon = True
        if params['founddate']:
            conditon = (Customer.founddate >= params['founddate'][0]) \
                    & (Customer.founddate <= params['founddate'][1])
        where_conditionAssigned = (MyCustomer.status.in_([MYCUSTOMER_STATUS_UNSIGNED, \
                                                        MYCUSTOMER_STATUS_SIGNED,\
                                                        MYCUSTOMER_STATUS_VISITED,\
                                                        MYCUSTOMER_STATUS_TRACKED, MYCUSTOMER_STATUS_TRANSED])) |\
                                                        (MyCustomer.updatetime > (datetime.datetime.now() - datetime.timedelta(days = 3))) # 三天内联系过的客户不允许取得
        phones = MyCustomer.select(Customer.phone).join(Customer, JOIN.RIGHT_OUTER, on=(Customer.id == MyCustomer.customer_id)).where(where_conditionAssigned)
        where_condition = (Customer.phone.not_in(phones)) & (Customer.dept_id == user.dept_id) \
                                    & conditon \
                                    & (Customer.assignetype == CUSTOMER_ASSIGNETYPE_AUTO)
        customers = Customer.select(Customer.id).where(where_condition).order_by(fn.Rand()).limit(100)
        print(customers)
        count = 0
        for customer in customers:
            '''因多人同时操作，需要检查在我的客户中是否存在（即是否被别人获取了）'''
            findcount = MyCustomer.select().where((MyCustomer.customer_id == customer.id) 
                                                  & (MyCustomer.status.in_([MYCUSTOMER_STATUS_UNSIGNED, \
                                                        MYCUSTOMER_STATUS_SIGNED,\
                                                        MYCUSTOMER_STATUS_VISITED,\
                                                        MYCUSTOMER_STATUS_TRACKED, MYCUSTOMER_STATUS_TRANSED]))).count()
            if findcount>0:
                pass
            else:
                count = count + 1
                #计算截止日期
                cur_date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                # 无类别客户1天期限
                enddatetime_str = (datetime.datetime.now()+datetime.timedelta(days=SALE_TYPE_1DAY)).strftime("%Y-%m-%d %H:%M:%S")
                MyCustomer.create(
                    customer_id = customer.id,
                    saletype=SALE_TYPE_NONE,
                    weixin = MYCUSTOMER_WEIXIN_NONE,
                    adddatetime=cur_date_str,
                    enddatetime =enddatetime_str,
                    tracker_id = params['userid'],
                    status=MYCUSTOMER_STATUS_UNSIGNED
                    )
        if count > 0:
            return super().resultSet(200, str(count)+"个客户添加成功", [])
        else:
            return super().resultSet(400, "公共客户数量不足！", [])
        raise Exception("添加失败")
 
    @db.atomic()
    def expireCustomer(self):
        """
                        设定过期的我的客户
        """
#         whereis = (MyCustomer.enddatetime < datetime.date.today()) \
#                 & (MyCustomer.status.not_in([MYCUSTOMER_STATUS_EXPIRE, MYCUSTOMER_STATUS_SIGNED,MYCUSTOMER_STATUS_TRANSED]))
#         mys = MyCustomer.select(MyCustomer.customer_id).where(whereis)
#         for rec in mys:
#             customer = Customer.get(Customer.id== rec.customer_id)
#             customer.updatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
#             customer.status = CUSTOMER_STATUS_UNASSIGNED
#             customer.save()
#             
#         MyCustomer.update(
#             {MyCustomer.status: MYCUSTOMER_STATUS_EXPIRE}
#             ).where(whereis).execute()
        
        return "过期客户已使用MYSQL定时任务"
    
    @db.atomic()
    def moveto(self, param):
        """
                        释放我的客户到公共客户或移动到其他跟踪者
        """
        if param["target"] == CUSTOMER_TYPE_COMM:

            for id in param["mycusIds"]:
                # 我的客户状态设已释放
                mycus = MyCustomer.get(MyCustomer.id == id)
                mycus.status = MYCUSTOMER_STATUS_FREE
                mycus.save()
        else:
            for id in param["mycusIds"]:
                # 我的客户状态设已释放
                mycus = MyCustomer.get(MyCustomer.id == id)
                mycus.tracker_id = param["trackerid"]
                mycus.save()
#                 # 业务统计
#                 # 接收人要累加
#                 self.summaryForMovetoAdd(param["trackerid"], mycus)

        return super().resultSet(200, "移动成功", [])
        raise Exception("移动失败")

    @db.atomic()                   
    def getoutdate(self, param):
        """
        捡漏
        """

        count = MyCustomer.select().where((MyCustomer.tracker_id==param['trackerid']) \
                                          & (MyCustomer.adddatetime.between(datetime.date.today(),\
                                                                            datetime.date.today() + datetime.timedelta(days=1)))).count()
        if count >= SALE_CUSTOMER_MAX:
            return super().resultSet(400, "每天只能添加"+str(SALE_CUSTOMER_MAX)+"个客户", [])

        #计算截止日期
        cur_date_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        # 无类别客户1天期限
        enddatetime_str = (datetime.datetime.now()+datetime.timedelta(days=SALE_TYPE_1DAY)).strftime("%Y-%m-%d %H:%M:%S")

        count = 0
        where_conditionAssigned=(MyCustomer.status.in_([MYCUSTOMER_STATUS_UNSIGNED,\
                                                        MYCUSTOMER_STATUS_SIGNED,\
                                                        MYCUSTOMER_STATUS_VISITED,\
                                                        MYCUSTOMER_STATUS_TRACKED,MYCUSTOMER_STATUS_TRANSED]))
        for id in param["mycusIds"]:
            '''因多人同时操作，需要检查在我的客户中是否存在（即是否被别人获取了）'''
            findcount = MyCustomer.select().where(where_conditionAssigned & MyCustomer.id == id).count()
            if findcount>0:
                pass
            else:
                mycus = MyCustomer.get(MyCustomer.id == id)
                mycus.status = MYCUSTOMER_STATUS_UNSIGNED
                mycus.saletype=SALE_TYPE_NONE
                mycus.adddatetime=cur_date_str
                mycus.enddatetime =enddatetime_str
                mycus.updatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                mycus.tracker_id = param['trackerid']
                mycus.save()
                count = count +1
        
        if count > 0:
            return super().resultSet(200, "捡漏成功" + str(count) + "个客户。", [])
        else:
            return super().resultSet(201, "捡漏失败，已被其他人捡漏。", [])
        raise Exception("数据库操作失败")

    @db.atomic()
    def typeto(self, param):
        """
                        批量客户分类
        """
        for myid in param["mycusIds"]:

            # 找到指定客户
            mycustomer=MyCustomer.get(MyCustomer.id==myid)
            #添加修改记录
            TrackRecord.create(
                mycustomer_id = mycustomer.id,
                tracktype = TRACK_EDIT,
                createtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                content = "客户类别：" + mycustomer.saletype + ">" + param["saletype"]
            )
            # 找到最新跟踪记录
            tarck = TrackRecord.select().where(TrackRecord.mycustomer_id ==myid).order_by(TrackRecord.createtime.desc()).first()
            if tarck:
                updatetime = tarck.createtime
            else:
                updatetime = mycustomer.adddatetime
            if param["saletype"]==SALE_TYPE_NONE:
                # 无类别客户批量自动1天期限
                enddatetime_str = (updatetime +datetime.timedelta(days=SALE_TYPE_1DAY)).strftime("%Y-%m-%d %H:%M:%S")
            elif param["saletype"]==SALE_TYPE_A:
                # A类别客户7天期限
                enddatetime_str = (updatetime+datetime.timedelta(days=SALE_TYPE_7DAY)).strftime("%Y-%m-%d %H:%M:%S")
            elif param["saletype"]==SALE_TYPE_B:
                # B类别客户14天期限
                enddatetime_str = (updatetime+datetime.timedelta(days=SALE_TYPE_15DAY)).strftime("%Y-%m-%d %H:%M:%S")
            elif param["saletype"]==SALE_TYPE_C:
                # C类别客户30天期限
                enddatetime_str = (updatetime+datetime.timedelta(days=SALE_TYPE_30DAY)).strftime("%Y-%m-%d %H:%M:%S")
            else:
                # 无类别客户三天期限
                enddatetime_str = (updatetime+datetime.timedelta(days=SALE_TYPE_1DAY)).strftime("%Y-%m-%d %H:%M:%S")
            mycustomer.enddatetime = enddatetime_str
            mycustomer.saletype = param["saletype"]
            mycustomer.save()
            
            # 业务统计
            data = {
                       "trackerid":mycustomer.tracker_id,
                       "saletype":param["saletype"],
                       "isbatch" : True
                       }

            self.summaryForAdd(data)

        return super().resultSet(200, "批量分类成功", [])
        raise Exception("批量分类失败")

    def getMycustomercompany(self, userid):
        """取得用户应用列表 id：用户ID"""
        data = []
        mycustomers = MyCustomer.select().where((MyCustomer.tracker_id == userid) \
                    & ((MyCustomer.status == MYCUSTOMER_STATUS_SIGNED) \
                       | (MyCustomer.status == MYCUSTOMER_STATUS_TRACKED)\
                       | (MyCustomer.status == MYCUSTOMER_STATUS_VISITED)))
        print(mycustomers)
        for mycustomer in mycustomers:
            customer = Customer.select().where(Customer.id == mycustomer.customer_id).first()
            if customer == None:
                print(mycustomer.customer_id)
                continue
            data.append({"id":mycustomer.id, "customerId":mycustomer.customer_id, "customername":customer.compname})
        return super().resultSet(200, "我的客户取得成功！", data)


if __name__ == '__main__':
    whereis = (MyCustomer.enddatetime < datetime.date.today()) \
             & (MyCustomer.status.not_in([MYCUSTOMER_STATUS_EXPIRE, MYCUSTOMER_STATUS_SIGNED,MYCUSTOMER_STATUS_TRANSED]))
    
#     whereis = (MyCustomer.enddatetime < datetime.date.today()) \
#             & (MyCustomer.status.not_in([MYCUSTOMER_STATUS_EXPIRE, MYCUSTOMER_STATUS_SIGNED,MYCUSTOMER_STATUS_TRANSED]))
#     mys = MyCustomer.select(MyCustomer.customer_id).where(whereis)
#     for rec in mys:
#         customer = Customer.get(Customer.id== rec.customer_id)
#         customer.updatetime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
#         customer.status = CUSTOMER_STATUS_UNASSIGNED
#         customer.save()
#          
#     MyCustomer.update(
#         {MyCustomer.status: MYCUSTOMER_STATUS_EXPIRE}
#         ).where(whereis).execute()
